<template>
  <div class="space-y-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between">
      <div>
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">成果展示</h2>
        <p class="mt-1 text-sm text-gray-500">展示植物研究的重要成果</p>
      </div>
      <button 
        class="mt-4 md:mt-0 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-custom flex items-center"
        @click="openDialog()"
      >
        <i class="fa fa-plus mr-2"></i>
        <span>新增成果</span>
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-custom p-6">
      <div class="flex flex-col md:flex-row md:items-center gap-4">
        <div class="flex-1">
          <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
              <i class="fa fa-search"></i>
            </span>
            <input 
              v-model="searchQuery" 
              type="text" 
              class="pl-10 pr-4 py-2 w-full border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom" 
              placeholder="搜索成果标题..."
            >
          </div>
        </div>
        <div class="flex items-center gap-4">
          <el-select v-model="typeFilter" placeholder="成果类型" clearable>
            <el-option label="论文发表" value="paper" />
            <el-option label="专利授权" value="patent" />
            <el-option label="科研项目" value="project" />
            <el-option label="获奖情况" value="award" />
          </el-select>
          <el-select v-model="yearFilter" placeholder="发布年份" clearable>
            <el-option
              v-for="year in years"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 成果列表 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        v-for="achievement in filteredAchievements" 
        :key="achievement.id" 
        class="bg-white rounded-xl shadow-custom overflow-hidden hover:shadow-lg transition-custom group"
      >
        <div class="relative">
          <img 
            :src="achievement.image || 'https://picsum.photos/400/200'" 
            :alt="achievement.title"
            class="w-full h-48 object-cover"
          >
          <div class="absolute top-3 right-3 space-x-2">
            <button 
              class="p-2 bg-white/90 rounded-lg text-primary hover:bg-primary hover:text-white transition-custom"
              @click.stop="openDialog(achievement)"
            >
              <i class="fa fa-edit"></i>
            </button>
            <button 
              class="p-2 bg-white/90 rounded-lg text-danger hover:bg-danger hover:text-white transition-custom"
              @click.stop="confirmDelete(achievement)"
            >
              <i class="fa fa-trash"></i>
            </button>
          </div>
          <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-4">
            <span class="px-2 py-1 bg-primary/90 text-white text-xs rounded-full">
              {{ achievement.type | achievementType }}
            </span>
          </div>
        </div>
        <div class="p-4">
          <h3 class="text-lg font-semibold text-gray-800 line-clamp-2 group-hover:text-primary transition-custom">
            {{ achievement.title }}
          </h3>
          <p class="mt-2 text-sm text-gray-500 line-clamp-2">{{ achievement.description }}</p>
          <div class="mt-4 flex items-center justify-between text-sm">
            <div class="flex items-center text-gray-500">
              <i class="fa fa-calendar-alt mr-2"></i>
              <span>{{ achievement.date }}</span>
            </div>
            <div class="flex items-center text-gray-500">
              <i class="fa fa-user mr-2"></i>
              <span>{{ achievement.author }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="flex items-center justify-between bg-white rounded-xl shadow-custom p-4">
      <div class="text-sm text-gray-500">
        共 {{ totalAchievements }} 条记录
      </div>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :total="totalAchievements"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="成果标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入成果标题" />
        </el-form-item>
        <el-form-item label="成果类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择成果类型">
            <el-option label="论文发表" value="paper" />
            <el-option label="专利授权" value="patent" />
            <el-option label="科研项目" value="project" />
            <el-option label="获奖情况" value="award" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="成果描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入成果描述"
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="mt-2 text-xs text-gray-500">
            建议尺寸：800x400，支持 jpg、png 格式，大小不超过 2MB
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="400px"
    >
      <p>确定要删除"{{ deleteAchievement?.title }}"吗？此操作不可恢复。</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleDelete" :loading="deleting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AchievementList',
  filters: {
    achievementType(value) {
      const types = {
        paper: '论文发表',
        patent: '专利授权',
        project: '科研项目',
        award: '获奖情况'
      }
      return types[value] || value
    }
  },
  data() {
    return {
      // 搜索和筛选
      searchQuery: '',
      typeFilter: '',
      yearFilter: '',
      
      // 分页
      currentPage: 1,
      pageSize: 9,

      // 表单对话框
      dialogVisible: false,
      submitting: false,
      form: {
        id: null,
        title: '',
        type: '',
        date: '',
        author: '',
        description: '',
        image: ''
      },

      // 删除对话框
      deleteDialogVisible: false,
      deleting: false,
      deleteAchievement: null,

      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入成果标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择成果类型', trigger: 'change' }
        ],
        date: [
          { required: true, message: '请选择发布日期', trigger: 'change' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入成果描述', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ]
      },

      // 模拟数据
      achievements: [
        {
          id: 1,
          title: '银杏叶提取物的制备方法及其应用',
          type: 'patent',
          date: '2024-01-15',
          author: '张三',
          description: '本发明提供了一种从银杏叶中提取银杏内酯的新方法，具有提取效率高、成本低的特点。',
          image: 'https://picsum.photos/400/200?random=1'
        },
        {
          id: 2,
          title: '人参皂苷对神经细胞保护作用的研究',
          type: 'paper',
          date: '2024-02-20',
          author: '李四',
          description: '研究发现人参皂苷具有显著的神经保护作用，可能成为治疗神经退行性疾病的新药物。',
          image: 'https://picsum.photos/400/200?random=2'
        },
        {
          id: 3,
          title: '中药材种植技术创新项目',
          type: 'project',
          date: '2024-03-01',
          author: '王五',
          description: '运用现代农业技术提高中药材种植效率和质量的研究项目。',
          image: 'https://picsum.photos/400/200?random=3'
        }
      ]
    }
  },
  computed: {
    dialogTitle() {
      return this.form.id ? '编辑成果' : '新增成果'
    },
    years() {
      const currentYear = new Date().getFullYear()
      return Array.from({ length: 10 }, (_, i) => currentYear - i)
    },
    filteredAndSortedAchievements() {
      let result = [...this.achievements]

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item => 
          item.title.toLowerCase().includes(query) ||
          item.description.toLowerCase().includes(query)
        )
      }

      // 类型过滤
      if (this.typeFilter) {
        result = result.filter(item => item.type === this.typeFilter)
      }

      // 年份过滤
      if (this.yearFilter) {
        result = result.filter(item => item.date.startsWith(this.yearFilter))
      }

      // 按日期降序排序
      result.sort((a, b) => new Date(b.date) - new Date(a.date))

      return result
    },
    totalAchievements() {
      return this.filteredAndSortedAchievements.length
    },
    filteredAchievements() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredAndSortedAchievements.slice(start, end)
    }
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page
    },
    openDialog(achievement = null) {
      if (achievement) {
        this.form = { ...achievement }
      } else {
        this.resetForm()
      }
      this.dialogVisible = true
    },
    resetForm() {
      this.form = {
        id: null,
        title: '',
        type: '',
        date: '',
        author: '',
        description: '',
        image: ''
      }
      this.$refs.form?.resetFields()
    },
    beforeImageUpload(file) {
      const isJPGOrPNG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPGOrPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPGOrPNG && isLt2M
    },
    handleImageSuccess(res, file) {
      // 这里应该处理实际的上传响应
      // 目前使用本地预览
      this.form.image = URL.createObjectURL(file.raw)
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        this.submitting = true

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        if (this.form.id) {
          // 更新现有成果
          const index = this.achievements.findIndex(item => item.id === this.form.id)
          if (index !== -1) {
            this.achievements[index] = { ...this.form }
          }
        } else {
          // 添加新成果
          this.achievements.push({
            ...this.form,
            id: this.achievements.length + 1
          })
        }

        this.$message.success(this.form.id ? '更新成功' : '添加成功')
        this.dialogVisible = false
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        this.submitting = false
      }
    },
    confirmDelete(achievement) {
      this.deleteAchievement = achievement
      this.deleteDialogVisible = true
    },
    async handleDelete() {
      if (!this.deleteAchievement) return

      try {
        this.deleting = true
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        const index = this.achievements.findIndex(item => item.id === this.deleteAchievement.id)
        if (index !== -1) {
          this.achievements.splice(index, 1)
        }

        this.$message.success('删除成功')
        this.deleteDialogVisible = false
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      } finally {
        this.deleting = false
        this.deleteAchievement = null
      }
    }
  }
}
</script>

<style scoped>
.transition-custom {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.shadow-custom {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style> 